package com.android.clinic.app.ui.personal;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.android.clinic.app.ClinicApplication;
import com.android.clinic.app.R;
import com.android.clinic.app.base.BaseActivity;
import com.android.clinic.app.entity.UserInfo;
import com.android.clinic.app.glide.ImageLoaderUtils;
import com.android.clinic.app.http.HttpClient;
import com.android.clinic.app.http.base.BaseObserver;
import com.android.clinic.app.http.utils.RxObservableUtils;
import com.android.clinic.app.ui.widget.AccordionTextView;
import com.android.clinic.app.ui.widget.dialog.CustomSheetSexDialog;
import com.android.clinic.app.utils.Constants;
import com.android.clinic.app.utils.DisplayUtil;
import com.android.clinic.app.utils.PhotoUtils;
import com.android.clinic.app.utils.PreferencesUtils;
import com.android.clinic.app.utils.Utils;
import com.bigkoo.pickerview.OptionsPickerView;
import com.jiongbull.jlog.JLog;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by cheng on 2018/2/5.
 * 个人信息
 */
public class PersonalActivity extends BaseActivity {

    private PhotoUtils photoUtils;

    private ImageView ivHead;
    private AccordionTextView tvLivingHabit, tvGender, tvIdCard,
            tvRealName, tvOccupation, tvAllergy, tvHistory, tvMarriage;

    private OptionsPickerView pvOptions;
    private ArrayList<String> optionsItems = new ArrayList<>();
    private HashMap<String, Integer> marriageMap = new HashMap<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        photoUtils = new PhotoUtils(this);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_personal;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        setTitleBarTitle("个人信息");
        setTitleBarLeftResource(R.drawable.icon_back);

        ivHead = (ImageView) findViewById(R.id.iv_head);
        tvLivingHabit = (AccordionTextView) findViewById(R.id.tv_living_habit);
        tvGender = (AccordionTextView) findViewById(R.id.tv_gender);
        tvIdCard = (AccordionTextView) findViewById(R.id.tv_card_number);
        tvRealName = (AccordionTextView) findViewById(R.id.tv_real_name);
        tvOccupation = (AccordionTextView) findViewById(R.id.tv_occupation);
        tvAllergy = (AccordionTextView) findViewById(R.id.tv_allergy_history);
        tvHistory = (AccordionTextView) findViewById(R.id.tv_disease_history);
        tvMarriage = (AccordionTextView) findViewById(R.id.tv_marriage_situation);

        initOptionData();
        initMarriageSituation();

        UserInfo userInfo = ClinicApplication.getUserInfo();
        ImageLoaderUtils.getInstance().loadHeadImage(userInfo.getImgUrl(), ivHead,
                DisplayUtil.dip2px(60), DisplayUtil.dip2px(60));
        // 姓名
        tvRealName.setTextValue(!Utils.isEmpty(userInfo.getName()) ? userInfo.getName() : "请填写");
        // 性别
        tvGender.setTextValue(!Utils.isEmpty(userInfo.getGender()) ? userInfo.getGender() : "请填写");
        // 身份证
        tvIdCard.setTextValue(!Utils.isEmpty(userInfo.getIdCard()) ? userInfo.getIdCard() : "请填写");
        // 婚育情况
        tvMarriage.setTextValue(!Utils.isEmpty(userInfo.getMarriage())
                ? Utils.getMapKey(marriageMap, Integer.valueOf(userInfo.getMarriage())) : "请填写");
        // 疾病史
        if (TextUtils.isEmpty(PreferencesUtils.getString(this, "history"))){
             tvHistory.setTextValue(!Utils.isEmpty(userInfo.getHistory()) ? userInfo.getHistory() : "请填写");
        } else {
             tvHistory.setTextValue(PreferencesUtils.getString(this, "history"));
        }
        // 过敏史
        if (TextUtils.isEmpty(PreferencesUtils.getString(this, "allergy"))){
            tvAllergy.setTextValue(!Utils.isEmpty(userInfo.getAllergy()) ? userInfo.getAllergy() : "请填写");
        } else {
            tvAllergy.setTextValue(PreferencesUtils.getString(this, "allergy"));
        }
        // 职业
        tvOccupation.setTextValue(!Utils.isEmpty(userInfo.getProfessional()) ? userInfo.getProfessional(): "请填写");
        // 生活习惯
        tvLivingHabit.setTextValue(!Utils.isEmpty(userInfo.getLiveHabit()) ? userInfo.getLiveHabit() : "请填写");

    }

    private void initOptionData() {
        optionsItems.add("已婚");
        optionsItems.add("未婚");
        optionsItems.add("离异");
        optionsItems.add("丧偶");
        optionsItems.add("未生育");
        optionsItems.add("备孕期");
        optionsItems.add("怀孕期");
        optionsItems.add("已生育");

        marriageMap.put("未婚", 0);
        marriageMap.put("已婚", 1);
        marriageMap.put("离异", 2);
        marriageMap.put("丧偶", 3);
        marriageMap.put("未生育", 4);
        marriageMap.put("备孕期", 5);
        marriageMap.put("怀孕期", 6);
        marriageMap.put("已生育", 7);

    }

    @Override
    protected void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            // 修改头像
            case R.id.layout_update_head:
                photoUtils.showPhotoDialog();
                break;
            // 修改姓名
            case R.id.tv_real_name:
                Intent intent = new Intent(this, UpdateActivity.class);
                intent.putExtra("type", "0");
                intent.putExtra("realName", tvRealName.getTextValue());
                startActivityForResult(intent, UpdateActivity.NAME_CODE);
                break;
            // 修改性别
            case R.id.tv_gender:
                updateSex();
                break;
            // 身份证件号
            case R.id.tv_card_number:
                intent = new Intent(this, UpdateActivity.class);
                intent.putExtra("type", "1");
                intent.putExtra("cardNumber", tvIdCard.getTextValue());
                startActivityForResult(intent, UpdateActivity.CARD_NUMBER_CODE);
                break;
            // 修改职业
            case R.id.tv_occupation:
                intent = new Intent(this, UpdateActivity.class);
                intent.putExtra("type", "2");
                intent.putExtra("occupation", tvOccupation.getTextValue());
                startActivityForResult(intent, UpdateActivity.OCCUPATION_CODE);
                break;
            // 婚育情况
            case R.id.tv_marriage_situation:
                pvOptions.show();
                break;
            // 过敏史
            case R.id.tv_allergy_history:
                intent = new Intent(this, AllergyHistoryActivity.class);
                intent.putExtra("type", "0");
                intent.putExtra("allergy", tvAllergy.getTextValue());
                startActivityForResult(intent, AllergyHistoryActivity.ALLERGY_CODE);
                break;
            // 疾病史
            case R.id.tv_disease_history:
                intent = new Intent(this, AllergyHistoryActivity.class);
                intent.putExtra("type", "1");
                intent.putExtra("history", tvHistory.getTextValue());
                startActivityForResult(intent, AllergyHistoryActivity.ALLERGY_CODE);
                break;
            // 生活习惯
            case R.id.tv_living_habit:
                startActivityForResult(new Intent(this, LivingHabitActivity.class).putExtra("livingHabit",
                        tvLivingHabit.getTextValue().replace("请填写,","")),
                        LivingHabitActivity.LIVING_CODE);
                break;
        }
    }

    /**
     * 更改用户性别
     */
    private void updateSex() {
        new CustomSheetSexDialog(PersonalActivity.this).builder().setCancelable(true).setCanceledOnTouchOutside(true)
                .setOnSheetItemClickListener(which -> {
                       if (which == 1) {
                           tvGender.setTextValue("女");
                       } else {
                           tvGender.setTextValue("男");
                       }
                    updateGender(tvGender.getTextValue().trim());
                }).show();
    }

    /**
     * 选择婚育情况
     */
    private void initMarriageSituation() {
        pvOptions = new OptionsPickerView.Builder(this, (options1, options2, options3, v) -> {
            tvMarriage.setTextValue(optionsItems.get(options1));
            updateMarriage(marriageMap.get(optionsItems.get(options1)));
        }).setTitleText("婚育情况")
                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0, 1)//默认选中项
                .isCenterLabel(false)
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();

        pvOptions.setPicker(optionsItems);//一级选择器
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            // 生活习惯
            if (requestCode == LivingHabitActivity.LIVING_CODE) {
                String livingHabit = data.getStringExtra("livingHabit").replace("请填写,", "");
                if (!TextUtils.isEmpty(livingHabit)) {
                    JLog.e("livingHabit:  " + livingHabit);
                    tvLivingHabit.setTextValue(livingHabit);
                    updateLiveHabit(livingHabit);
                }
            } // 姓名
            else if(requestCode == UpdateActivity.NAME_CODE){
                String nickName = data.getStringExtra("realName");
                if (!TextUtils.isEmpty(nickName)) {
                    tvRealName.setTextValue(nickName);
                    updateRealName(nickName);
                }
            } // 身份证件号
            else if(requestCode == UpdateActivity.CARD_NUMBER_CODE){
                String cardNumber = data.getStringExtra("cardNumber");
                if (!TextUtils.isEmpty(cardNumber)) {
                    tvIdCard.setTextValue(cardNumber);
                    updateIdCard(cardNumber);
                }
            } // 职业
            else if(requestCode == UpdateActivity.OCCUPATION_CODE){
                String occupation = data.getStringExtra("occupation");
                if (!TextUtils.isEmpty(occupation)) {
                    tvOccupation.setTextValue(occupation);
                    updateProfessional(occupation);
                }
            } // 过敏史/疾病史
            else if(requestCode == AllergyHistoryActivity.ALLERGY_CODE) {
                String allergy = data.getStringExtra("allergy");
                String history = data.getStringExtra("history");
                if (!TextUtils.isEmpty(allergy)) {
                    tvAllergy.setTextValue(allergy);
                    PreferencesUtils.putString(PersonalActivity.this,"allergy",allergy);
                    updateAllergy(allergy);
                }
                if (!TextUtils.isEmpty(history)) {
                    tvHistory.setTextValue(history);
                    PreferencesUtils.putString(PersonalActivity.this,"history",history);
                    updateHistory(history);
                }

            } else {
                photoUtils.onActivityResult(requestCode, resultCode, data, new PhotoUtils.ResultListener() {
                    @Override
                    public void crop(String photoPath) {
                        upLoadFile(photoPath);
                    }
                });
            }
        }
    }

    /**
     * 上传头像
     * @param imageUri
     */
    private void upLoadFile(String imageUri) {
        final File file = new File(imageUri);
        if(file.exists()){
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            MultipartBody.Part body =
                    MultipartBody.Part.createFormData("file", file.getName(), requestFile);
            HttpClient.getHttpService().uploadSingleTypeFile(body)
                    .compose(this.bindToLifecycle())
                    .compose(RxObservableUtils.applySchedulers(loading, "上传中..."))
                    .subscribe(new BaseObserver<String>() {
                        @Override
                        public void onSuccess(String s) {
                            ImageLoaderUtils.getInstance().loadHeadImage(s, ivHead);
                            updateHeadImg(s);
                        }

                        @Override
                        public void onFailure(String message) {
                            showToast(message);
                        }
                    });
        }
    }

    /**
     * 上传头像
     * @param imgUrl
     */
    private void updateHeadImg(String imgUrl) {
        HttpClient.getHttpService().updateHeadImg(ClinicApplication.getUserInfo().getId(), imgUrl)
                .compose(this.bindToLifecycle())
                .compose(RxObservableUtils.applySchedulers(loading, ""))
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        Constants.isUpdate = true;
                        showToast("头像上传成功!");
                    }

                    @Override
                    public void onFailure(String message) {
                        showToast(message);
                    }
                });
    }


    /**
     * 更新姓名
     * @param realName
     */
    private void updateRealName(String realName) {
        HttpClient.getHttpService().updateRealName(ClinicApplication.getUserInfo().getId(), realName)
                .compose(this.bindToLifecycle())
                .compose(RxObservableUtils.applySchedulers(loading, ""))
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        Constants.isUpdate = true;
                        showToast("信息更改成功!");
                    }

                    @Override
                    public void onFailure(String message) {
                        showToast(message);
                    }
                });
    }


    /**
     * 更改用户性别
     * @param gender
     */
    private void updateGender(String gender) {
        HttpClient.getHttpService().updateGender(ClinicApplication.getUserInfo().getId(), gender)
                .compose(this.bindToLifecycle())
                .compose(RxObservableUtils.applySchedulers(loading, ""))
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        Constants.isUpdate = true;
                        showToast("信息更改成功!");
                    }

                    @Override
                    public void onFailure(String message) {
                        showToast(message);
                    }
                });
    }


    /**
     * 更新身份证件号
     * @param idCard
     */
    private void updateIdCard(String idCard) {
        HttpClient.getHttpService().updateIdCard(ClinicApplication.getUserInfo().getId(), idCard)
                .compose(this.bindToLifecycle())
                .compose(RxObservableUtils.applySchedulers(loading, ""))
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        Constants.isUpdate = true;
                        showToast("信息更改成功!");
                    }

                    @Override
                    public void onFailure(String message) {
                        showToast(message);
                    }
                });
    }

    /**
     * 更新职业
     * @param professional
     */
    private void updateProfessional(String professional) {
        HttpClient.getHttpService().updateProfessional(ClinicApplication.getUserInfo().getId(), professional)
                .compose(this.bindToLifecycle())
                .compose(RxObservableUtils.applySchedulers(loading, ""))
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        Constants.isUpdate = true;
                        showToast("信息更改成功!");
                    }

                    @Override
                    public void onFailure(String message) {
                        showToast(message);
                    }
                });
    }

    /**
     * 更新婚育情况
     * @param marriage
     */
    private void updateMarriage(int marriage) {
        HttpClient.getHttpService().updateMarriage(ClinicApplication.getUserInfo().getId(), marriage)
                .compose(this.bindToLifecycle())
                .compose(RxObservableUtils.applySchedulers(loading, ""))
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        Constants.isUpdate = true;
                        showToast("信息更改成功!");
                    }

                    @Override
                    public void onFailure(String message) {
                        showToast(message);
                    }
                });
    }

    /**
     * 更新生活习惯
     * @param liveHabit
     */
    private void updateLiveHabit(String liveHabit) {
        HttpClient.getHttpService().updateLiveHabit(ClinicApplication.getUserInfo().getId(), liveHabit)
                .compose(this.bindToLifecycle())
                .compose(RxObservableUtils.applySchedulers(loading, ""))
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        Constants.isUpdate = true;
                        showToast("信息更改成功!");
                    }

                    @Override
                    public void onFailure(String message) {
                        showToast(message);
                    }
                });
    }

    /**
     * 更新过敏史
     * @param allergy
     */
    private void updateAllergy(String allergy) {
        HttpClient.getHttpService().updateAllergy(ClinicApplication.getUserInfo().getId(), allergy)
                .compose(this.bindToLifecycle())
                .compose(RxObservableUtils.applySchedulers(loading, ""))
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        Constants.isUpdate = true;
                        showToast("信息更改成功!");
                    }

                    @Override
                    public void onFailure(String message) {
                        showToast(message);
                    }
                });
    }

    /**
     * 更疾病史
     * @param history
     */
    private void updateHistory(String history) {
        HttpClient.getHttpService().updateHistory(ClinicApplication.getUserInfo().getId(), history)
                .compose(this.bindToLifecycle())
                .compose(RxObservableUtils.applySchedulers(loading, ""))
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        Constants.isUpdate = true;
                        showToast("信息更改成功!");
                    }

                    @Override
                    public void onFailure(String message) {
                        showToast(message);
                    }
                });
    }


}
